import router from './router'
import store from './store'
import { Toast, Notify } from 'vant'

import { getToken, setToken } from '@/utils/auth'
import defaultSettings from '@/settings'
import tools from '@/utils/tools'

const whiteList = ['login']
var loadingInstance = null
function startLoading() {
  loadingInstance = Toast.loading({
    duration: 0, // 持续展示 toast
    forbidClick: true,
    message: '页面渲染中...'
  })
}
function endLoading() {
  if (loadingInstance) {
    Toast.clear()
  }
}
router.beforeEach(async(to, from, next) => {
  if (!tools.isDeviceMobile()) {
    Notify('为了更好的体验，请使用手机打开！')
  }
  startLoading()
  document.title = defaultSettings.title

  const hasToken = getToken()
  if (!hasToken) {
    if (to.query.accessToken) {
      store.commit('SET_TOKEN', to.query.accessToken)
      setToken(to.query.accessToken)
    }
  }
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      endLoading()
    } else {
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          const { roles } = await store.dispatch('getInfo')

          const accessRoutes = await store.dispatch('generateRoutes', roles)

          router.addRoutes(accessRoutes)

          next({ ...to, replace: true })
        } catch (error) {
          console.error(error)
          await store.dispatch('resetToken')
          next(`/login?redirect=${to.path}`)
          endLoading()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.name) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      endLoading()
    }
  }
})

router.afterEach(() => {
  endLoading()
})
